<?php 
namespace App\Http\Controllers\MobileApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\Mysql\pre_ucenter_members;
use App\Models\Mysql\pre_forum_pollvoter;

use Cookie;

class LoginController extends Controller
{
	use GlobalData;

	const ROUTE_PREFIX = '/api/*';

	protected $request;

	protected $curTime;

	protected $debug;


	/**
	 * 创建新的`LogoutController`控制器实例
	 * @param \Illuminate\Http\Request $request
	 */
	public function __construct(Request $request)
	{
		$this->request = $request;
		$this->error = [];
		$this->curTime = time();

		if(config('app.debug')) {
			$this->debug = true;
			error_reporting(E_ALL | E_STRICT);
		} else {
			$this->debug = false;
		}
	}

    #登录接口
    public function login()
    {

        $p = $_REQUEST;
        $username =isset($p['username']) ?  addslashes(trim($p['username'])) : '';
        $password = isset($p['password']) ?  addslashes(trim($p['password'])) : '';
//        file_put_contents('1.log','时间：'.date('Y-m-d H:i:s',time())."\n". var_export($_REQUEST,true),8);
        if(empty($password) ||empty($username))
        {
            $data = array(
                'code' => 5,
                'msg' => '亲，用户名或密码不能为空',
            );
            exit(json_encode($data));
        }
        $param=['username'=>$username,'password'=>$password];
        list($r, $reason)=pre_ucenter_members::check($param);
//        md5(md5('ZY8866zy').'c66e9f');
        if($r)
        {
            $certified = (empty(pre_forum_pollvoter::check($r[0]->uid)) ? 0 :1);
			$data = array(
                'code' => 200,
                'msg' => '亲，登录成功',
                'result' => array(
					'uid'=> $r[0]->uid,
					'userName'=> $r[0]->userName,
					'certified'=>$certified
					)
            );
            session_start();
            $_SESSION['uid']=$r[0]->uid;
            $_SESSION['user_name']=$username;
            $_SESSION['certified']=$certified;
			//Cookie::queue('test', 'Hello, Laravel', 10);
			//$result = setrawcookie('PHPSESSID',session_id(),time()+3600*24*30);
			//file_put_contents("/lishu.txt","setcookie ok".$result,8);
			/*$result2 = $_COOKIE["PHPSESSID"];
			file_put_contents("/lishu.txt","getcookie ok".print_r($result2,TRUE),8);*/
            /*setcookie('uid',$_SESSION['uid'],3600*24);
            setcookie('user_name',$_SESSION['user_name'],3600*24);
            setcookie('certified',$_SESSION['certified'],3600*24);*/
            exit(json_encode($data));
        }
        else
        {
			if ($reason=='UserNotExist'){
				$data = array(
					'code' => 222,
					'msg' => '亲，用户名不存在',
					'result' => [],
				);
				exit(json_encode($data));
			}
			else{
				$data = array(
					'code' => 223,
					'msg' => '亲，密码错误',
					'result' => [],
				);
				exit(json_encode($data));
			}
        }
    }
	
	/**
	 * API: 退出登录接口(logout)
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function logout()
	{
		try {
			if(!isset($_SESSION)){
				session_start();
			}
			foreach(array('uid','user_name','certified') as $v){
				if(isset($_SESSION[$v])){
					unset($_SESSION[$v]);
				}
			}
			/*if(isset($_SESSION['uid'])){
				unset($_SESSION['uid']);
			}
			if(isset($_SESSION['user_name'])){
				unset($_SESSION['user_name']);
			}
			if(isset($_SESSION['certified'])){
				unset($_SESSION['certified']);
			}*/
			
			return json_encode(array('code' => 200,'msg' => '退出登录成功','result' => []));

		} catch (\Exception $e) {
			if($this->debug) {
				return responseJson(__FILE__.':'.__FUNCTION__.':'.__LINE__.':'.$e->getMessage());
			}
			return responseJson($e->getMessage());
		}
	}

	/**
	 * API: 退出登录接口(logout)
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function loginStatus()
	{
		try {
			/*if (!empty($_COOKIE['PHPSESSID']))
				echo $_COOKIE['PHPSESSID'];
			else
				echo "not exist";*/
			if(!isset($_SESSION)){
				session_start();
			}
			if(isset($_SESSION['uid']) && isset($_SESSION['user_name'])  && isset($_SESSION['certified'])){
				//$certified=pre_forum_pollvoter::check((int)$_SESSION['uid']);
				return json_encode(array(
					'code' => 200,'msg' => '获取登录状态成功',
					'result' => array('uid'=>$_SESSION['uid'],'userName'=>$_SESSION['user_name'],'certified'=>$_SESSION['certified']),
					));
			}
			else{
				return json_encode(array(
					'code' => 200,'msg' => '获取登录状态成功','result' => []
					));
			}

		} catch (\Exception $e) {
			if($this->debug) {
				return responseJson(__FILE__.':'.__FUNCTION__.':'.__LINE__.':'.$e->getMessage());
			}
			return responseJson($e->getMessage());
		}
	}
} //!- LoginController
?>
